package cn.lili.modules.payment.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.modules.kit.core.PaymentHttpResponse;
import cn.lili.modules.kit.core.enums.RequestMethodEnums;
import cn.lili.modules.kit.core.kit.PayKit;
import cn.lili.modules.kit.plugin.wechat.WechatApi;
import cn.lili.modules.payment.entity.dos.WechatApplyment;
import cn.lili.modules.payment.entity.enums.ApplymentStatusEnum;
import cn.lili.modules.payment.wechat.applyments.EcommerceDTO;
import cn.lili.modules.payment.wechat.applyments.UboInfo;
import cn.lili.modules.payment.wechat.enums.WechatApiEnum;
import cn.lili.modules.payment.wechat.enums.WechatDomain;
import cn.lili.modules.payment.wechat.model.profitsharing.ProfitSharing;
import cn.lili.modules.system.entity.dto.payment.WechatPaymentSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 电商收付通工具类
 */
@Slf4j
@Component
public class EcommerceUtil {
    @Autowired
    private WechatUtil wechatUtil;

    /**
     * 申请服务商
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_1_8.shtml
     *
     * @param ecommerceDTO 二级商户进件申请
     */
    public void applyment(EcommerceDTO ecommerceDTO, WechatApplyment wechatApplyment) {
        try {
            ecommerceDTO.setOut_request_no(wechatApplyment.getOutRequestNo());

            //营业执照日期string转string数组
            if (ecommerceDTO.getBusiness_license_info() != null) {
                String[] businessTime = ecommerceDTO.getBusiness_license_info().getBusiness_time().split(",");
                ecommerceDTO.getBusiness_license_info().setBusiness_time(JSONUtil.parse(businessTime).toString());
            }

            //加密
            this.uploadMedia(ecommerceDTO);
            //实体加密
            PayKit.encryptField(ecommerceDTO, wechatUtil.getPlatformCert());

            String jsonStr = JSONUtil.toJsonStr(ecommerceDTO);
            log.error("jsonStr:" + jsonStr);
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.POST,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.E_COMMERCE_APPLY.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    wechatUtil.getPlatformCert().getSerialNumber().toString(16),
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(ecommerceDTO)
            );
            log.info("进件响应 {}", response);
            //退款申请成功
            if (response.getStatus() == 200) {
                wechatApplyment.setStatus(ApplymentStatusEnum.APPLYMENT_STATE_AUDITING.name());
                wechatApplyment.setApplymentStateMsg(ApplymentStatusEnum.APPLYMENT_STATE_AUDITING.description());
                wechatApplyment.setApplymentId(JSONUtil.parseObj(response.getBody()).get("applyment_id").toString());
                wechatApplyment.setErrorMessage("");
            } else {
                wechatApplyment.setStatus(ApplymentStatusEnum.APPLYMENT_STATE_REJECTED.name());
                wechatApplyment.setErrorMessage(JSONUtil.parseObj(response.getBody()).get("message").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 查询申请状态
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/applyments/chapter3_2.shtml
     *
     * @param outRequestNo
     */
    public JSONObject applyments(String outRequestNo) {

        try {
            String branchesUrl = String.format(WechatApiEnum.E_COMMERCE_APPLY_STATE_BY_NO.toString(), outRequestNo);
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    branchesUrl,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("查询进件响应 {}", response);
            return JSONUtil.parseObj(response.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 二级商户号账户实时余额
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/pages/amount.shtml
     *
     * @param subMchid 二级商户号
     */
    public JSONObject subNowBalance(String subMchid) {
        try {
            String url = String.format(WechatApiEnum.QUERY_BALANCE.toString(), subMchid);
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    url,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("查询余额：" + response.getBody());

            return JSONUtil.parseObj(response.getBody());

        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }

    /**
     * 请求分账
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/profitsharing/chapter3_1.shtml
     */
    public JSONObject profitSharing(ProfitSharing profitSharing) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            profitSharing.setAppid(setting.getMpAppId());

            log.error("分账：" + JSONUtil.toJsonStr(profitSharing));

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.POST,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.PROFIT_SHARING_ORDERS.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(profitSharing)
            );
            log.info("分账：" + response.getBody());

            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询分账结果
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_4_2.shtml
     *
     * @param subMchid      二级商户号
     * @param transactionId 微信订单号
     * @param outOrderNo    商户分账单号
     */
    public JSONObject queryProfitSharing(String subMchid, String transactionId, String outOrderNo) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();

            String branchesUrl = WechatApiEnum.PROFIT_SHARING_ORDERS
                    + "?sub_mchid=" + subMchid
                    + "&transaction_id=" + transactionId
                    + "&out_order_no=" + outOrderNo;

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    branchesUrl,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("查询分账结果：" + response.getBody());

            return JSONUtil.parseObj(response.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询订单剩余待分金额
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_4_9.shtml
     *
     * @param transactionId 微信订单号
     */
    public Double queryProfitSharingOrdersUnsplitAmount(String transactionId) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            Map map = new HashMap<>();
            map.put("transaction_id", transactionId);

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.POST,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.PROFIT_SHARING_ORDERS_AMOUNTS.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(map)
            );
            log.info("查询订单剩余待分金额：" + response.getBody());

            return CurrencyUtil.reversalFen((int) JSONUtil.parseObj(response.getBody()).get("unsplit_amount"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加分账接收方
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/profitsharing/chapter3_7.shtml
     *
     * @param appid        公众账号ID
     * @param type         接收方类型
     * @param account      接收方账号
     * @param name         接收方名称
     * @param relationType 与分账方的关系类型
     */
    void addReceivers(String appid, String type, String account, String name, String relationType) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            Map map = new HashMap<>();
            map.put("appid", appid);
            map.put("type", type);
            map.put("account", account);
            map.put("name", name);
            map.put("relation_type", relationType);

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.POST,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.PROFIT_SHARING_RECEIVERS_ADD.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(map)
            );
            log.info("添加分账接收方：" + response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除分账接收方API
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/profitsharing/chapter3_8.shtml
     *
     * @param appid   公众账号ID
     * @param type    接收方类型
     * @param account 接收方账号
     */
    void deleteReceivers(String appid, String type, String account) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            Map map = new HashMap<>();
            map.put("appid", appid);
            map.put("type", type);
            map.put("account", account);

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.POST,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.PROFIT_SHARING_RECEIVERS_DELETE.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(map)
            );
            log.info("删除分账接收方API：" + response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 完结分账API
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/profitsharing/chapter3_5.shtml
     *
     * @param subMchid      二级商户号
     * @param transactionId 微信订单号
     * @param outOrderNo    商户分账单号
     * @param description   分账描述
     */
    void finishOrder(String subMchid, String transactionId, String outOrderNo, String description) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            Map map = new HashMap<>();
            map.put("sub_mchid", subMchid);
            map.put("transaction_id", transactionId);
            map.put("out_order_no", outOrderNo);
            map.put("description", description);

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.POST,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.PROFIT_SHARING_FINISH_ORDER.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(map)
            );
            log.info("完结分账API：" + response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 二级商户账户余额提现
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/fund/chapter3_2.shtml
     *
     * @param subMchid     二级商户号
     * @param amount       提现金额
     * @param outRequestNo 商户提现单号
     */
    public JSONObject subWithdraw(String subMchid, String outRequestNo, Integer amount) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            Map map = new HashMap<>();
            map.put("sub_mchid", subMchid);
            map.put("out_request_no", outRequestNo);
            map.put("amount", amount);

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.POST,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.WITHDRAW.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(map)
            );
            log.info("二级商户账户余额提现：" + response.getBody());
            return JSONUtil.parseObj(response.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 平台提现
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/fund/chapter3_5.shtml
     */
    void spWithdraw(String outRequestNo, Integer amount, String accountType) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            Map map = new HashMap<>();
            map.put("out_request_no", outRequestNo);
            map.put("amount", amount);
            map.put("account_type", accountType);

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.POST,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.MERCHANT_WITHDRAW.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(map)
            );
            log.info("平台提现：" + response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 二级商户查询提现状态
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/fund/chapter3_3.shtml
     *
     * @param subMchid     二级商户号
     * @param outRequestNo 商户提现单号
     */
    public JSONObject querySubWithdrawByOutRequestNo(String subMchid, String outRequestNo) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();

            String branchesUrl = String.format(WechatApiEnum.QUERY_WITHDRAW_BY_OUT_REQUEST_NO.toString(), outRequestNo) + "?sub_mchid=" + subMchid;

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    branchesUrl,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("二级商户查询提现状态：" + response.getBody());
            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 电商平台查询提现状态
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/fund/chapter3_6.shtml
     *
     * @param outRequestNo 商户提现单号
     */
    void querySpWithdrawByOutRequestNo(String outRequestNo) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            Map map = new HashMap<>();
            map.put("out_request_no", outRequestNo);

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.QUERY_MERCHANT_WITHDRAW_BY_OUT_REQUEST_NO.toString(),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(map)
            );
            log.info("电商平台查询提现状态：" + response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 申请交易账单API
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_9_1.shtml
     *
     * @param billDate 账单日期
     */
    public JSONObject tradeBill(String billDate) {
        try {

            log.info("调用 申请交易账单API 接口");
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.TRADE_BILL.toString() + "?bill_date=" + billDate,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("请求账单API：" + response.getBody());
            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 申请资金账单API
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_9_2.shtml
     *
     * @param billDate 账单日期
     */
    public JSONObject fundFlowBill(String billDate, String accountType) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.FUND_FLOW_BILL.toString() + "?bill_date=" + billDate + "&account_type=" + accountType,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("申请资金账单API：" + response.getBody());
            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 申请分账账单API
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_9_6.shtml
     *
     * @param billDate 账单日期
     */
    public JSONObject bills(String billDate) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.PROFITSHARING_BILLS.toString() + "?bill_date=" + billDate,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("申请资金账单API：" + response.getBody());
            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 申请二级商户资金账单API
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_9_5.shtml
     *
     * @param billDate 账单日期
     */
    public JSONObject ecommerceFundFlowBill(String billDate) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            Map map = new HashMap<>();
            map.put("bill_date", billDate);

            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.FUND_FLOW_BILL.toString() + "?bill_date=" + billDate + "&account_type=ALL&tar_type=GZIP&algorithm=AEAD_AES_256_GCM",
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    JSONUtil.toJsonStr(map)
            );
            log.info("申请资金账单API：" + response.getBody());
            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 下载账单
     * 文档地址: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_9_3.shtml
     */
    public String downloadBill(String downloadUrl) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();

            PaymentHttpResponse result = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    WechatApiEnum.BILL_DOWNLOAD.toString() + "?" + downloadUrl.substring(downloadUrl.indexOf("token=")),
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("result:{}", result);
            return result.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject combineQuery(String combineOutTradeNo) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            String url = String.format(WechatApiEnum.COMBINE_TRANSACTIONS_QUERY.toString(), combineOutTradeNo);
            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(), url,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("result:{}", response);

            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 订单查询
     * https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_2_5.shtml
     *
     * @param orderOutTradeNo
     * @return
     */
    public JSONObject orderQuery(String orderOutTradeNo, String subMchId) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            String url = String.format(WechatApiEnum.PARTNER_ORDER_QUERY_BY_NO.toString(), orderOutTradeNo) + "?sp_mchid=" + setting.getMchId() +
                    "&sub_mchid=" + subMchId;
            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(),
                    url,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("result:{}", response);

            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_6_2.shtml
     * 查询退款
     *
     * @return
     */
    public JSONObject refundQuery(String outRefundNo, String subMchId) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();
            String url = String.format(WechatApiEnum.QUERY_REFUNDS_BY_REFUND_NO.toString(), outRefundNo) + "?sub_mchid=" + subMchId;
            PaymentHttpResponse response = WechatApi.v3(
                    RequestMethodEnums.GET,
                    WechatDomain.CHINA.toString(), url,
                    setting.getMchId(),
                    setting.getSerialNumber(),
                    null,
                    setting.getApiclient_key(),
                    ""
            );
            log.info("result:{}", response);

            return JSONUtil.parseObj(response.getBody());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 上传证件图片
     *
     * @param ecommerceDTO 二级商户进件申请
     */
    private void uploadMedia(EcommerceDTO ecommerceDTO) {


        //营业执照/登记证书信息
        if (ecommerceDTO.getBusiness_license_info() != null) {
            if (StrUtil.isNotBlank(ecommerceDTO.getBusiness_license_info().getBusiness_license_copy())) {
                ecommerceDTO.getBusiness_license_info().setBusiness_license_copy(this.uploadMediaV3(ecommerceDTO.getBusiness_license_info().getBusiness_license_copy()));
            }
        }
        //金融机构许可证信息
        if (ecommerceDTO.getFinance_institution_info() != null) {

        }
        //法定代表人说明函
        if (ecommerceDTO.getAuthorize_letter_copy() != null
                && CharSequenceUtil.isNotBlank(ecommerceDTO.getAuthorize_letter_copy())) {
            ecommerceDTO.setAuthorize_letter_copy(this.uploadMediaV3(ecommerceDTO.getAuthorize_letter_copy()));
        }
        //经营者/法人身份证信息
        if (ecommerceDTO.getId_card_info() != null) {
            //身份证人像面照片
            if (StrUtil.isNotBlank(ecommerceDTO.getId_card_info().getId_card_copy())) {
                ecommerceDTO.getId_card_info().setId_card_copy(
                        this.uploadMediaV3(ecommerceDTO.getId_card_info().getId_card_copy()));
            }
            //身份证国徽面照片
            if (StrUtil.isNotBlank(ecommerceDTO.getId_card_info().getId_card_national())) {
                ecommerceDTO.getId_card_info().setId_card_national(
                        this.uploadMediaV3(ecommerceDTO.getId_card_info().getId_card_national()));
            }
        }
        //最终受益人信息列表
        if (ecommerceDTO.getUbo_info_list() != null) {
            for (UboInfo UboInfo : ecommerceDTO.getUbo_info_list()) {
                //身份证人像面照片
                if (StrUtil.isNotBlank(UboInfo.getUbo_id_doc_copy())) {
                    UboInfo.setUbo_id_doc_copy(
                            this.uploadMediaV3(UboInfo.getUbo_id_doc_copy()));
                }
                //身份证国徽面照片
                if (StrUtil.isNotBlank(UboInfo.getUbo_id_doc_copy_back())) {
                    UboInfo.setUbo_id_doc_copy_back(
                            this.uploadMediaV3(UboInfo.getUbo_id_doc_copy_back()));
                }
            }
        }
        //超级管理员信息
        if (ecommerceDTO.getContact_info() != null) {
            //超级管理员证件正面照片
            if (StrUtil.isNotBlank(ecommerceDTO.getContact_info().getContact_id_doc_copy())) {
                ecommerceDTO.getContact_info().setContact_id_doc_copy(
                        this.uploadMediaV3(ecommerceDTO.getContact_info().getContact_id_doc_copy()));
            }
            //超级管理员证件反面照片
            if (StrUtil.isNotBlank(ecommerceDTO.getContact_info().getContact_id_doc_copy_back())) {
                ecommerceDTO.getContact_info().setContact_id_doc_copy_back(
                        this.uploadMediaV3(ecommerceDTO.getContact_info().getContact_id_doc_copy_back()));
            }
            //业务办理授权函
            if (StrUtil.isNotBlank(ecommerceDTO.getContact_info().getBusiness_authorization_letter())) {
                ecommerceDTO.getContact_info().setBusiness_authorization_letter(
                        this.uploadMediaV3(ecommerceDTO.getContact_info().getBusiness_authorization_letter()));
            }
        }
        //店铺信息
        if (ecommerceDTO.getSales_scene_info() != null) {
            //店铺二维码
            if (StrUtil.isNotBlank(ecommerceDTO.getSales_scene_info().getStore_qr_code())) {
                ecommerceDTO.getSales_scene_info().setStore_qr_code(
                        this.uploadMediaV3(ecommerceDTO.getSales_scene_info().getStore_qr_code()));
            }
        }
    }


    private String uploadMediaV3(String mediaFileUrl) {
        try {
            WechatPaymentSetting setting = wechatUtil.wechatPaymentSetting();

            File file = this.getFile(mediaFileUrl);
            String sha256 = SecureUtil.sha256(file);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("filename", file.getName());
            map.put("sha256", sha256);

            PaymentHttpResponse response =
                    WechatApi.v3(
                            WechatDomain.CHINA.toString(),
                            WechatApiEnum.MERCHANT_UPLOAD_MEDIA.toString(),
                            setting.getMchId(),
                            setting.getSerialNumber(),
                            null,
                            setting.getApiclient_key(),
                            JSONUtil.toJsonStr(map),
                            file
                    );

            log.error("媒体上传：" + response.getBody());
            return JSONUtil.parseObj(response.getBody()).get("media_id").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }


}
